<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1200"
        destroy-on-close
        @closed="$emit('closed')"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <!-- <el-col :span="6">
                    <el-form-item label-width="80px" label="还货单位:">
                        <el-tooltip placement="top">
                            <template #content>
                                联系人: {{entityObj.purchaseRealName}}
                                <br />
                                联系电话:{{entityObj.purchaseMobile}}
                                <br />
                                联系地址:{{entityObj.purchaseAddress}}
                            </template>
                            <span style="color: blue;">{{entityObj.purchaseUnityName}}</span>
                        </el-tooltip>
                    </el-form-item>
                </el-col>-->
                <el-col :span="6">
                    <el-form-item label-width="80px" label="还货人" prop="backGoodsName">
                        <el-input
                            placeholder="---请输入还货人---"
                            v-model="entityObj.backGoodsName"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="80px" label="还货时间" prop="backGoodsDate">
                        <el-date-picker
                            v-model="entityObj.backGoodsDate"
                            :default-time="defaultTime"
                            type="datetime"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            placeholder="请输入采购时间"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="80px" label="借货单位" prop="taskOrgId">
                        <sc-supplier-select
                            ref="taskSupplierSelect"
                            :queryType="'supplier/purchase-unity-org-pages'"
                            :defaultQueryList="{purchaseType:3}"
                            :props="orgProps"
                            :selectKeyValue="'key'"
                            :multiple="false"
                            v-model="entityObj.taskOrgs"
                            @fatherMethod="taskSupplierSelectProcess"
                        ></sc-supplier-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="80px" label="收货单位" prop="taskOrgId">
                        <el-select
                            placeholder="---请选择收货单位---"
                            v-model="entityObj.taskSubOrgId"
                            @change="taskSupplierChange"
                            style="width: 250px"
                        >
                            <el-option
                                v-for="item in taskSubSupplierOptions"
                                :key="item.supplierId"
                                :label="item.supplierName"
                                :value="item.supplierId"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label-width="80px" label="收货地址" prop="address">
                        <el-input
                            placeholder="---请输入收货地址---"
                            v-model="entityObj.address"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="80px" label="联系人" prop="realName">
                        <el-input
                            placeholder="---请输入收货人---"
                            v-model="entityObj.realName"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label-width="80px" label="联系电话" prop="mobile">
                        <el-input
                            placeholder="---请输入联系电话---"
                            v-model="entityObj.mobile"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="80px" label="还货订单" prop="purchaseOrderItems">
                        <el-button size="small" @click="addBorrowMaterial()">还货</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="80px">
                        <el-table
                            :data="entityObj.backGoodsOrderItems"
                            border
                            style="width: 100%"
                            show-summary
                        >
                            <el-table-column label="操作">
                                <template #default="scope">
                                    <div
                                        @click="deleteBackRow(scope.$index, scope.row)"
                                        class="del-temp-but"
                                    >移除</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="物料编码" width="130" prop="materialCode"></el-table-column>
                            <el-table-column label="物料名称" width="130" prop="materialName">
                                <template #default="scope">
                                    <div
                                        v-if="scope.row.materialImages && scope.row.materialImages.length > 0"
                                        style="color: #318cf2;"
                                        @click="handlePreview(scope.row)"
                                    >{{scope.row.materialName}}</div>
                                    <div v-else>{{scope.row.materialName}}</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="规格" width="130" prop="materialSpecs"></el-table-column>
                            <el-table-column label="物料类别" width="130" prop="materialTypeName"></el-table-column>
                            <el-table-column label="单位" width="100" prop="unitName"></el-table-column>
                            <el-table-column prop="waitBackQty" label="待还数量" min-width="95"></el-table-column>
                            <el-table-column prop="backQty" label="还货数量" min-width="130">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.backQty"
                                        style="width: 100%"
                                        :step="1"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="出库仓库" prop="warehouseId" min-width="140">
                                <template #default="scope">
                                    <el-select
                                        placeholder="---请选择出库仓库 ---"
                                        v-model="scope.row.warehouseId"
                                        style="width: 100%"
                                    >
                                        <el-option
                                            v-for="item in scope.row.warehouseStocks"
                                            :key="item.warehouseId"
                                            :label="item.warehouseName"
                                            :value="item.warehouseId"
                                        />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="仓库库存" min-width="110" prop="stockQty">
                                <template
                                    #default="scope"
                                >{{scope.row.stockQty= scope.row.warehouseStocks.find(p=>p.warehouseId==scope.row.warehouseId)?.stockQty}}</template>
                            </el-table-column>
                            <el-table-column label="备注" min-width="160" prop="remarks">
                                <template #default="scope">
                                    <el-input v-model="scope.row.remarks" style="width: 100%" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="borrowQty" label="借货数量" min-width="95"></el-table-column>
                            <el-table-column prop="alreadyBackQty" label="已还数量" min-width="95"></el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="handleBeforeClose">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit">保 存</el-button>
        </template>
    </full-screen-dialog>
    <!-- 预览组件 -->
    <el-image-viewer
        v-if="showImage"
        @close="closeViewer"
        :hide-on-click-modal="true"
        :url-list="srcList"
    />

    <!-- 借出订单记录 -->
    <template>
        <el-dialog
            v-model="borrowPurchaseOrderState"
            title="还货"
            :width="1300"
            :center="true"
            append-to-body
            style="height: 540px"
        >
            <el-row style="margin-bottom: 50px;">
                <sc-borrow-goods-order-choice
                    ref="scBorrowPurchaseOrderChoice"
                    :defaultQueryList="borrowQueryList"
                ></sc-borrow-goods-order-choice>
            </el-row>
            <template #footer>
                <el-button @click="borrowPurchaseOrderState = false">取 消</el-button>
                <el-button
                    type="primary"
                    :loading="isSaveing"
                    @click="setBorrowPurchaseOrderChoice"
                >确定</el-button>
            </template>
        </el-dialog>
    </template>
</template>



<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            visible: false,
            active: 2,
            stepList: ["已下单", "处理中", "已完成"],
            orgType: 3,
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                backGoodsOrderItems: [],
            },
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            orgProps: {
                label: "supplierName",
                value: "key",
            },
            //还货
            borrowPurchaseOrderState: false,
            borrowQueryList: {},
            taskSubSupplierOptions: [],
        };
    },
    computed: {},
    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //图片预览
        handlePreview(row) {
            console.log("row", row.materialImages);
            if (!row.materialImages || row.materialImages.length == 0) {
                return;
            }
            this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
            this.srcList = row.materialImages; // 设置预览列表
            this.showImage = true; // 显示 el-image
        },
        closeViewer() {
            this.showImage = false;
        },
        //表单注入数据
        async setData(data) {
            //this.entityObj = {...data};
        },
        submit(status) {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    try {
                        let data = structuredClone(this.entityObj);
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add" 
                                    ? "back-goods-order/create"
                                    : "back-goods-order/update",
                                { ...data }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //收货供应商
        async taskSupplierSelectProcess(rowData) {
            if (
                this.entityObj.backGoodsOrderItems &&
                this.entityObj.backGoodsOrderItems.length > 0
            ) {
                await this.$confirm(
                    "修改借货供应商，会将所有的还货信息清空？",
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(() => {
                        this.setTaskSupplier(rowData);
                    })
                    .catch(() => {
                        this.entityObj.taskOrgs = {
                            key: this.entityObj.taskOrgKey,
                            supplierName: this.entityObj.taskOrgName,
                        };
                        return;
                    });
            } else {
                this.setTaskSupplier(rowData);
            }
        },
        //设置收货供应商
        async setTaskSupplier(rowData) {
            this.entityObj.taskOrgs = {
                key: rowData.key,
                supplierName: rowData.supplierName,
            };
            this.entityObj.taskOrgKey = rowData.key;
            this.entityObj.taskOrgType = rowData.orgType;
            this.entityObj.taskOrgId = rowData.supplierId;
            this.entityObj.taskOrgName = rowData.supplierName;

            var returnValue = await this.$API.auth.GetProcessApi.get(
                `supplier/${rowData.supplierId}/back-suppliers?isSelf=true`
            );
            if (returnValue.status == 200) {
                this.taskSubSupplierOptions = returnValue.response;
                if (
                    this.taskSubSupplierOptions &&
                    this.taskSubSupplierOptions.length > 0
                ) {
                    this.entityObj.taskSubOrgId=this.taskSubSupplierOptions[0].supplierId;
                    this.entityObj.realName =
                        this.taskSubSupplierOptions[0].realName;
                    this.entityObj.mobile =
                        this.taskSubSupplierOptions[0].mobile;
                    this.entityObj.address =
                        this.taskSubSupplierOptions[0].address;
                }
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
            this.entityObj.backGoodsOrderItems = [];
        },
        async taskSupplierChange(supplierId) {
            const subSupplier = this.taskSubSupplierOptions.find(
                (p) => p.supplierId == supplierId
            );
            this.entityObj.realName = subSupplier.realName;
            this.entityObj.mobile = subSupplier.mobile;
            this.entityObj.address = subSupplier.address;
        },
        async getPurchaseUnity() {
            //采购单位列表
            var returnValue = await this.$API.auth.GetProcessApi.get(
                "purchase-unity/current"
            );
            if (returnValue.status == 200) {
                this.entityObj.purchaseUnityId =
                    returnValue.response.purchaseUnityId;
                this.entityObj.purchaseUnityName =
                    returnValue.response.purchaseUnityName;
                this.entityObj.purchaseRealName = returnValue.response.realName;
                this.entityObj.purchaseMobile = returnValue.response.mobile;
                this.entityObj.purchaseAddress = returnValue.response.address;
            } else {
                this.$message.error("操作失败:" + returnValue.msg);
            }
        },
        //还货
        addBorrowMaterial() {
            if (!this.entityObj.taskOrgId) {
                this.$message.error("请先选择收货供应商");
                return;
            }

            this.borrowPurchaseOrderState = true;
            this.borrowQueryList = { supplierId: this.entityObj.taskOrgId };
            this.$nextTick(() => {
                this.$refs.scBorrowPurchaseOrderChoice.opBindData();
            });
        },
        //还货
        setBorrowPurchaseOrderChoice() {
            if (
                !this.entityObj.backGoodsOrderItems ||
                this.entityObj.backGoodsOrderItems.length == 0
            ) {
                this.entityObj.backGoodsOrderItems = [];
            }

            let materials =
                this.$refs.scBorrowPurchaseOrderChoice.selectionRows;
            materials.map((p) => {
                this.entityObj.backGoodsOrderItems.push({
                    operateOrderType: p.operateOrderType,
                    operateOrderId: p.operateOrderId,
                    operateOrderItemId: p.operateOrderItemId,
                    operateOrderCode:p.operateOrderCode,
                    borrowGoodsOrderItemId:p.borrowGoodsOrderItemId,
                    borrowGoodsOrderId:p.borrowGoodsOrderId,
                    borrowGoodsOrderCode:p.borrowGoodsOrderCode,
                    supplierName: p.supplierName,
                    materialId: p.materialId,
                    materialItemId: p.materialItemId,
                    materialCode: p.materialCode,
                    materialName: p.materialName,
                    materialSpecs: p.materialSpecs,
                    materialTypeId: p.materialTypeId,
                    materialTypeName: p.materialTypeName,
                    unitCode: p.unitCode,
                    unitName: p.unitName,
                    waitBackQty: p.waitBackQty,
                    backQty: p.waitBackQty,
                    alreadyBackQty: p.alreadyBackQty,
                    borrowQty: p.borrowQty,
                    warehouseStocks: p.warehouseStocks,
                    warehouseId:
                        p.warehouseStocks && p.warehouseStocks.length > 0
                            ? p.warehouseStocks[0].warehouseId
                            : 0,
                    stockQty:
                        p.warehouseStocks && p.warehouseStocks.length > 0
                            ? p.warehouseStocks[0].stockQty
                            : 0,
                });
            });
            this.borrowPurchaseOrderState = false;
        },
        //删除
        deleteBackRow(index) {
            this.entityObj.backGoodsOrderItems.splice(index, 1);
        },
        async initOptions() {},
    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        this.entityObj.backGoodsName = tool.data.get("USER_INFO").Name;
        this.entityObj.backGoodsDate = tool.formatDate(new Date(), 1);
        this.getPurchaseUnity();
        console.log(this.entityObj);
    },
};
</script>

<style scoped>
.el-form-item {
    margin-bottom: 5px !important;
}

.del-temp-but {
    text-align: center;
    width: 46px;
    height: 24px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #318cf2;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #318cf2;
}
</style>
